<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['nongjt:area:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >{{ isExpandAll ? '折叠' : '展开' }}</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="areaList"
      row-key="code"
      :tree-props="{children: 'children'}"
      :default-expand-all="isExpandAll"
    >
      <el-table-column label="区域编码" prop="code" />
      <el-table-column label="父编码" align="center" prop="parentCode" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="标识" align="center" prop="unit">
        <template #default="scope">
          <span v-if="scope.row.unit === 0">市</span>
          <span v-else-if="scope.row.unit === 1">区/县</span>
          <span v-else-if="scope.row.unit === 2">街道</span>
          <span v-else-if="scope.row.unit === -1">省</span>
          <span v-else>{{ scope.row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nongjt:area:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['nongjt:area:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nongjt:area:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改地区层级关系对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="areaRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入区域编码" />
        </el-form-item>
        <el-form-item label="父编码" prop="parentCode">
          <el-tree-select
            v-model="form.parentCode"
            :data="areaOptions"
            :props="{ value: 'code', label: 'name', children: 'children' }"
            value-key="code"
            placeholder="请选择父编码"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="标识" prop="unit">
          <el-form-item>
            <el-select
                v-model="form.unit"
                placeholder="请选择状态"
                clearable
                style="width: 200px"
            >
              <el-option label="省" :value="-1"  disabled/>
              <el-option label="市" :value="0" />
              <el-option label="区/县" :value="1" />
              <el-option label="街道" :value="2" />
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="状态" prop="status">
        <el-select
            v-model="form.status"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
        >
          <el-option label="停用" :value="0" />
          <el-option label="正常" :value="1" />
        </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Area">
import { listArea, getArea, delArea, addArea, updateArea } from "@/api/nongjt/area";

const { proxy } = getCurrentInstance();

const areaList = ref([]);
const areaOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const title = ref("");
const isExpandAll = ref(false);

const data = reactive({
  form: {},
  rules: {
  }
});

const { form, rules } = toRefs(data);

/** 查询地区层级关系列表 */
async function getList() {
  loading.value = true;
  try {
    // 加载所有数据
    const response = await listArea();
    if (response && response.data) {
      // 构造树形结构数据
      const treeData = proxy.handleTree(response.data, "code", "parentCode");
      areaList.value = treeData;
    } else {
      areaList.value = [];
    }
  } catch (error) {
    console.error("数据加载失败:", error);
    areaList.value = [];
  } finally {
    loading.value = false;
  }
}

/** 查询地区层级关系下拉树结构 */
async function getTreeselect() {
  try {
    // 加载所有数据用于下拉选择
    const response = await listArea();
    if (response && response.data) {
      areaOptions.value = [];
      const data = { code: 0, name: '顶级节点', children: [] };
      data.children = proxy.handleTree(response.data, "code", "parentCode");
      areaOptions.value.push(data);
    }
  } catch (error) {
    console.error("下拉树数据加载失败:", error);
  }
}

	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    code: null,
    parentCode: null,
    name: null,
    unit: null,
    status: 1
  };
  proxy.resetForm("areaRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.code) {
    form.value.parentCode = row.code;
  } else {
    form.value.parentCode = 0;
  }
  open.value = true;
  title.value = "添加地区层级关系";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  isExpandAll.value = !isExpandAll.value;
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentCode = row.parentCode;
  }
  getArea(row.id).then(response => {
    if (response && response.data) {
      form.value = response.data;
      open.value = true;
      title.value = "修改地区层级关系";
    }
  }).catch(error => {
    console.error("获取详情失败:", error);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["areaRef"].validate(valid => {
    if (valid) {
      // 新增时移除id字段，避免后端数据库错误
      const formData = { ...form.value };
      if (!formData.id) {
        delete formData.id;
      }
      
      if (form.value.id != null) {
        updateArea(formData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("修改失败:", error);
        });
      } else {
        addArea(formData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("新增失败:", error);
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除地区层级关系编号为"' + row.id + '"的数据项？').then(function() {
    return delArea(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 页面加载完成后获取数据
onMounted(() => {
  getList();
});
</script>

<script>
import { onMounted } from 'vue';
</script>